﻿<?php

/*********************************************************************************************/
/* Include
/*********************************************************************************************/

require_once 'RollingCurl/RollingCurl.php';
require_once 'Spiders/LIB_parse.php';
require_once 'Spiders/LIB_http.php';
define(LOG_PREFIX, "freebox");
require_once 'Logger/logger.php';
require_once 'Security/rsa.php';
require_once 'Tools/chronometer.php';
require_once 'Tools/lock.php';
require_once 'Tools/get.php';
require_once 'Tools/network.php';
require_once 'DB/db.php';
require_once 'Parser/form_fields.php';
require_once 'Parser/htmlconverter.php';
require_once 'Spiders/LIB_mail.php';
define(LANGUAGE, getValueGET('lang', 'fr'));

/*********************************************************************************************/
/* Wifi status
/*********************************************************************************************/

function getWifiData($fxCredentials) {
	return getFormData($fxCredentials, 'settings', 'wifi_client_params');
}

function getWifiStatus($fxCredentials) {

	$data = getWifiData($fxCredentials);
	if(isset($data['enabled']))
	return ($data['enabled'] == 'on');
	
	return false;	
}

function setWifiStatus($fxCredentials, $status) {

	if( $status != getWifiStatus($fxCredentials) )
	{
		$data = getWifiData($fxCredentials);	
		if($status)
		$data['enabled'] = 'on';
		else
		unset($data['enabled']);
		
		postData($fxCredentials, 'wifi', 'cgi', $data);		
		logFxAction("setWifiStatus", $fxCredentials, "Set wifi to " . ($status ? 'on' : 'off'));
	}
	else
	{
		logFxAction("setWifiStatus", $fxCredentials, "Nothing to do");
	}
}

/*********************************************************************************************/
/* Client management
/*********************************************************************************************/

function addMacToWhiteList($fxCredentials, $mac) {

	$data = array(
	'comment' => '',
	'bss_cfg_name' => 'perso',
	'mac' => $mac,
	'filter_type' => 'whitelist',
	'method' => 'wifi.mac_filter_add',
	'action' => 'Ajouter à la liste blanche'
	);
	postData($fxCredentials, 'wifi', 'cgi', $data);	
	logFxAction("addMacToWhiteList", $fxCredentials, "Add mac[$mac]");
	
}

function removeMacFromWhiteList($fxCredentials, $mac) {
	$data = array(
	'mac' => $mac,
	'filter_type' => 'whitelist',
	'method' => 'wifi.mac_filter_del',
	'action' => 'Supprimer'
	);
	postData($fxCredentials, 'wifi', 'cgi', $data);			
	logFxAction("removeMacFromWhiteList", $fxCredentials, "Remove mac[$mac]");
}

function addMacToBlackList($fxCredentials, $mac) {
	$data = array(
	'comment' => '',
	'bss_cfg_name' => 'perso',
	'mac' => $mac,
	'filter_type' => 'blacklist',
	'method' => 'wifi.mac_filter_add',
	'action' => 'Ajouter à la liste noire'
	);
	postData($fxCredentials, 'wifi', 'cgi', $data);
	logFxAction("addMacToBlackList", $fxCredentials, "Add mac[$mac]");
}

function removeMacFromBlackList($fxCredentials, $mac) {
	$data = array(
	'mac' => $mac,
	'filter_type' => 'blacklist',
	'method' => 'wifi.mac_filter_del',
	'action' => 'Supprimer'
	);
	postData($fxCredentials, 'wifi', 'cgi', $data);
	logFxAction("removeMacFromBlackList", $fxCredentials, "Remove mac[$mac]");
}

function getMacList($fxCredentials) {

	$ip = $fxCredentials['freeboxurl'];	
	$url = generateUrl($ip, 'settings');
	$param = array('page' => 'wifi_client_station');
	LogInfo("[getMacList] access mac client station from [$url]");
	$html = http_get_form($url, $url, $param);
	checkHtmlResponse($url, $result);
	
	$result = array();
	$stations = parse_array($html['FILE'], "<li mac=\"", "\" class=\"list_n2\">");
	foreach($stations as $station) {
		$station = str_replace("<li mac=\"", '', $station);
		$station = str_replace("\" class=\"list_n2\">", '', $station);
		$tag = getTagFromMag($fxCredentials, $station);
		if($tag !== $station)
			$result[] = array('mac' => $station, 'tag' => $tag);
		else
			$result[] = array('mac' => $tag);
	}
	
	//add already existing mac
	$userId = getUserId($fxCredentials);
	$sql = "select mac, tag from freebox_macs where user_id = $userId";
	$cursor = execSQL($sql);
	while( $row = mysql_fetch_array( $cursor ) ) {
		$isexist = false;
		foreach($result as $value) {
			if($value['mac'] == $row['mac']) {
				$isexist = true;
				break;
			}
		}
		if(!$isexist) {
			if($row['mac'] !== $row['tag'])
				$result[] = array('mac' => $row['mac'], 'tag' => $row['tag']);
			else
				$result[] = array('mac' => $row['mac']);
		}
	}
	
	logFxAction("getMacList", $fxCredentials, "get mac list");
	
	return $result;
}

function tagMacAddress($fxCredentials, $mac, $tag) {
	$userId = getUserId($fxCredentials);
	$sql = "select count(*) as nb from freebox_macs where user_id = $userId and mac = '$mac'";
	$row = execOneSQL($sql);
	$exists = ( $row['nb'] > 0 );
	if(!$exists) { 	
		$sql = "INSERT INTO freebox_macs VALUES ($userId, '$mac', '$tag')";
		insertSQL($sql);
	}
	else
	{
		$sql = "UPDATE freebox_macs SET tag = '$tag' WHERE user_id = $userId AND mac = '$mac'";
		execSQL($sql);
	}
	
	logFxAction("tagMacAddress", $fxCredentials, "tag mac[$mac] as tag[$tag]");
}

function getMacFromTag($fxCredentials, $tag) {
	$userId = getUserId($fxCredentials);
	
	$sql = "SELECT mac FROM freebox_macs WHERE user_id = $userId AND tag = '$tag'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	throw new FreeboxWifiSchedulerException(translate('NO_MAC_TAG', array($tag)));
	
	$mac = $row['mac'];
	logFxAction("getMacFromTag", $fxCredentials, "get mac[$mac] for tag[$tag]");
	return $mac;	
}

function getTagFromMag($fxCredentials, $mac) {
	$userId = getUserId($fxCredentials);
	
	$sql = "SELECT tag FROM freebox_macs WHERE user_id = $userId AND mac = '$mac'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	{
		logFxAction("getTagFromMag", $fxCredentials, "get tag[$mac] for mac[$mac]");
		return $mac;
	}
	
	$tag = $row['tag'];
	logFxAction("getTagFromMag", $fxCredentials, "get tag[$mac] for mac[$mac]");
	return $tag;
}

function getFilterStatus($fxCredentials) {

	$data = getWifiData($fxCredentials);
	return $data['mac_filter'];
}
/*
0 = disabled
1 = liste blanche
2 = liste noire
*/
function setFilterStatus($fxCredentials, $status) {
	if($status < 0 || $status > 2)
	throw new FreeboxWifiSchedulerException(translate('INVALID_FILTER_STATUS', array($status)));
	
	$wifiFilterTranslate[] = 'disabled';
	$wifiFilterTranslate[] = 'whitelist';
	$wifiFilterTranslate[] = 'blacklist';
	
	if( $wifiFilterTranslate[$status] != getFilterStatus($fxCredentials) )
	{
		$data = getWifiData($fxCredentials);	
		$data['mac_filter'] = $wifiFilterTranslate[$status];		
		postData($fxCredentials, 'wifi', 'cgi', $data);
		logFxAction("setMacFilter", $fxCredentials, "Set filtering to " . $data['mac_filter']);
	}
	else
	{
		logFxAction("setMacFilter", $fxCredentials, "Nothing to do");
	}
}

function refreshMacList($fxCredentials, $maclist) {
	$userId = getUserId($fxCredentials);
	foreach($maclist as $mac) {
		$mac = $mac['mac'];
		$sql = "select count(*) as nb from freebox_macs where user_id = $userId and mac = '$mac'";
		$row = execOneSQL($sql);
		$exists = ( $row['nb'] > 0 );
		if(!$exists) { 	
			$sql = "INSERT INTO freebox_macs VALUES ($userId, '$mac', '$mac')";
			insertSQL($sql);
		}
	}
	logFxAction("refreshMacList", $fxCredentials, "Refresh mac list");
}

/*********************************************************************************************/
/* Parental control
/*********************************************************************************************/

function getParentalData($fxCredentials) {
	return getFormData($fxCredentials, 'settings', 'net_lfilter');
}

function getParentalControlStatus($fxCredentials) {

	$data = getParentalData($fxCredentials);
	if(isset($data['lfilter_enabled']))
	return ($data['lfilter_enabled'] == 'on');
	
	return false;
}

function setParentalControlStatus($fxCredentials, $status) {

	if( $status != getParentalControlStatus($fxCredentials) )
	{
		$data = getParentalData($fxCredentials);	
		if($status)
		$data['lfilter_enabled'] = 'on';
		else
		unset($data['lfilter_enabled']);
		
		postData($fxCredentials, 'fw', 'cgi', $data);		
		logFxAction("setParentalControlStatus", $fxCredentials, "Set parental to " . ($status ? 'on' : 'off'));
	}
	else
	{
		logFxAction("setParentalControlStatus", $fxCredentials, "Nothing to do");
	}
}

/*********************************************************************************************/
/* Remote connexion
/*********************************************************************************************/

function getRemoteConnexionData($fxCredentials) {
	return getFormData($fxCredentials, 'settings', 'conn_config_remote');
}

function getRemoteConnexionStatus($fxCredentials) {

	$data = getRemoteConnexionData($fxCredentials);
	if(isset($data['http_enabled']))
	return ($data['http_enabled'] == 'on');
	
	return false;
}

function setRemoteConnexionStatus($fxCredentials, $status) {

	if( $status != getRemoteConnexionStatus($fxCredentials) )
	{
		$data = getRemoteConnexionData($fxCredentials);	
		if($status)
		$data['http_enabled'] = 'on';
		else
		unset($data['http_enabled']);
		
		$result = postData($fxCredentials, 'conn', 'cgi', $data);
		//TODO
		if (strpos ($result['FILE'], 'Déconnexion Freebox') === FALSE) {
			LogError("[setRemoteConnexionStatus] cannot change remote connexion for " . $fxCredentials['freeboxurl']);
			throw new FreeboxWifiSchedulerException(translate('CANNOT_CHANGE_REMOTE_CONNEXION'));
		}
		logFxAction("setRemoteConnexionStatus", $fxCredentials, "Set Remote Connexion to " . ($status ? 'on' : 'off'));
	}
	else
	{
		logFxAction("setRemoteConnexionStatus", $fxCredentials, "Nothing to do");
	}
}

/*********************************************************************************************/
/* Porn protection
/*********************************************************************************************/

$_GET['OPENDNS'] = array('208.67.222.123', '208.67.220.123');

function getPornProtectionData($fxCredentials) {
	return getFormData($fxCredentials, 'settings', 'net_dhcp');
}

function getPornProtectionStatus($fxCredentials) {
	$result = true;
	$data = getPornProtectionData($fxCredentials);
	$result = $result && (!isset($data['sticky_assign']));
	$result = $result && ($data['dns1'] == $_GET['OPENDNS'][0]);
	$result = $result && ($data['dns2'] == $_GET['OPENDNS'][1]);	
	return $result;
}

function getFreeboxLocalIP($fxCredentials) {
	$data = getFormData($fxCredentials, 'settings', 'net_lan');
	return $data['lan_ip'];
}


function setPornProtectionStatus($fxCredentials, $status) {

	if( $status != getPornProtectionStatus($fxCredentials) )
	{
		$data = getPornProtectionData($fxCredentials);
		if($status)
		{
			unset($data['sticky_assign']);
			$data['dns1'] = $_GET['OPENDNS'][0];
			$data['dns2'] = $_GET['OPENDNS'][1];
		}
		else
		{
			$data['sticky_assign'] = 'on';
			$data['dns1'] = getFreeboxLocalIP($fxCredentials);
			$data['dns2'] = '';
		}
		
		$result = postData($fxCredentials, 'dhcp', 'cgi', $data);
		logFxAction("setPornProtectionStatus", $fxCredentials, "Set Porn protection to " . ($status ? 'on' : 'off'));
	}
	else
	{
		logFxAction("setPornProtectionStatus", $fxCredentials, "Nothing to do");
	}
}

/*********************************************************************************************/
/* Account management
/*********************************************************************************************/

function connect($fxCredentials, $suspendOnFail = false) {
	$url = $fxCredentials['freeboxurl'];
	$post_data = 
	array(
	'login' => 'freebox',
	'passwd' => $fxCredentials['freeboxpass'],
	'Entrer' => '',
	'id' => 'pass'
	);
	LogInfo("[connect] connect from [$url]");
	$result = postData($fxCredentials, 'login', 'php', $post_data);
	if (strpos ($result['FILE'], 'Déconnexion Freebox') === FALSE) {
		if($suspendonfail === true) {
			suspend($fxCredentials, 'B');
			LogError("[connect] freebox password was changed for $url");
			throw new FreeboxWifiSchedulerException(translate('FREEBOX_PWD_CHANGED', array($url)));
		}
		
		LogError("[connect] bad password or ip for $url");
		throw new FreeboxWifiSchedulerException(translate('BAD_IP_OR_PWD'));
	}
	
	$logout = return_between($result['FILE'], '<a id="link_login" href="', '">', EXCL);
	$logout = generateUrl($fxCredentials['freeboxurl'], $logout, '', null);
	return $logout;
}

function disconnect($fxCredentials) {
	$url = $fxCredentials['logout'];
	LogInfo("[disconnect] disconnect from [$url]");
	$result = http_get_form($url, $url, null);
	checkHtmlResponse($url, $result);
	if (strpos ($result['FILE'], 'Accès Freebox Server') === FALSE) {
		LogError("[disconnect] cannot disconnect from $url");
		throw new FreeboxWifiSchedulerException(translate('CANNOT_DISCONNECT'));
	}
}

function getFreeboxCredentials($email, $pass) {
	if(!isset($email))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_EMPTY'));
	
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_BAD', array($email)));

	//TODO pass = PASSWORD('$pass')";
	$sql = "SELECT freeboxurl, freeboxpass, activated FROM freebox_users WHERE LOWER(email) = LOWER('$email') AND pass = '$pass'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	
	throw new FreeboxWifiSchedulerException(translate('EMAIL_PWD_BAD', array($email)));
	if($row['activated'] == 'N')
	throw new FreeboxWifiSchedulerException(translate('ACCOUNT_NOT_ACTIVATED', array($email)));
	return $row;
}

function getUserId($fxCredentials) {
	$ip = $fxCredentials['freeboxurl'];
	$sql = "SELECT user_id FROM freebox_users WHERE freeboxurl = '$ip'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	throw new FreeboxWifiSchedulerException(translate('URL_BAD', array($ip)));
	return $row[0];
}

function curPageURL() {
	$pageURL = 'http';
	if (isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	
	$paramIdx = strpos ($pageURL, '?');
	if($paramIdx != FALSE)
	$pageURL = substr($pageURL, 0, $paramIdx);
	
	return $pageURL;
}

function getUniqueCode($length = "")
{	
	$code = md5(uniqid(rand(), true));
	if ($length != "") return substr($code, 0, $length);
	else return $code;
}

function register($email, $pass, $freeboxurl, $freeboxpass) {
	if(!isset($email))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_EMPTY'));
	
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_BAD', array($email)));

	$sql = "SELECT user_id FROM freebox_users WHERE email = '$email'";
	$row = execOneSQL($sql);
	if(is_array($row))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_ALREADY_USED', array($email)));
	
	if(!isset($pass))
	throw new FreeboxWifiSchedulerException(translate('PWD_EMPTY'));
	
	if(strlen($pass) < 4)
	throw new FreeboxWifiSchedulerException(translate('PWD_TOO_SHORT', array(4)));

	if(!isset($freeboxurl))
	throw new FreeboxWifiSchedulerException(translate('FREEBOX_URL_EMPTY'));
	
	if(strlen($freeboxurl) < 2)
	throw new FreeboxWifiSchedulerException(translate('FREEBOX_URL_BAD', array($freeboxurl)));
	
	$sql = "SELECT user_id FROM freebox_users WHERE freeboxurl = '$freeboxurl'";
	$row = execOneSQL($sql);
	if(is_array($row))
	throw new FreeboxWifiSchedulerException(translate('FREEBOX_URL_ALREADY_USED', array($freeboxurl)));	
	
	if(!isset($freeboxpass))
	throw new FreeboxWifiSchedulerException(translate('FREEBOX_PWD_EMPTY'));

	if(strlen($freeboxpass) < 4)
	throw new FreeboxWifiSchedulerException(translate('FREEBOX_PWD_TOO_SHORT', array(4)));
	
	try
	{
		//Try to ping freebox
		$url = generateUrl($freeboxurl, 'login');
		$result = http_get_form($url, $url, null);
		checkHtmlResponse($url, $result);
	}
	catch(Exception $e)
	{
		throw new FreeboxWifiSchedulerException(translate('FREEBOX_CONNECT_ERROR', array($freeboxurl)));
	}
	
	//Try to connect to freebox
	try
	{
		$fxCredentials = array('freeboxurl' => $freeboxurl, 'freeboxpass' => $freeboxpass);
		$fxCredentials['logout'] = connect($fxCredentials);
		disconnect($fxCredentials);
		
	}
	catch(Exception $e)
	{
		throw new FreeboxWifiSchedulerException(translate('FREEBOX_PWD_BAD'));
	}	
	
	$token = getUniqueCode(64);
	$activateUrl = curPageURL() . "?action=activate&email=$email&token=$token";
	
	$sql = "INSERT IGNORE INTO freebox_users ( email, pass, freeboxurl, freeboxpass, token, activated) VALUES ('$email', '$pass', '$freeboxurl', '$freeboxpass', '$token', 'N')";

	insertSQL($sql);
	
	$subject = "Activate freebox account";
	$msg = "To activate your account, please go to $activateUrl";
	
	$message = $msg;
	$address['to'] = $email;
	$address['from'] = "freebox@" . getServerAdress();
	$content_type = "Text/plain";
	formatted_mail($subject, $message, $address, $content_type);
	
	logFxAction("register", null, "Register " . $email);
}

function activate($email, $token) {
	
	$sql = "SELECT user_id, token, activated FROM freebox_users WHERE email = '$email'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_NOT_EXIST', array($email)));
	
	if($row['token'] !== $token)
	throw new FreeboxWifiSchedulerException(translate('EMAIL_ACTIVATE_ERROR', array($email)));
	
	if($row['activated'] !== 'N')
	throw new FreeboxWifiSchedulerException(translate('EMAIL_ALREADY_ACTIVATED', array($email)));

	$userId = $row['user_id'];
	$sql = "UPDATE freebox_users SET activated = 'Y' where user_id = $userId";
	execSQL($sql);
	logFxAction("activate", null, "Activate " . $email);
}

function unregister($fxCredentials) {
	$userId = getUserId($fxCredentials);
	$sql = "DELETE FROM freebox_users where user_id = $userId";
	execSQL($sql);
	logFxAction("unregister", $fxCredentials, "Unregister " . $fxCredentials['freeboxurl']);
}

function suspend($fxCredentials, $status = 'S') {
	$userId = getUserId($fxCredentials);
	$sql = "UPDATE freebox_users SET activated = '$status' where user_id = $userId";
	execSQL($sql);
	logFxAction("suspend", $fxCredentials, "Suspend " . $fxCredentials['freeboxurl']);
}

function checkstatus($fxCredentials, $status) {
	$userId = getUserId($fxCredentials);
	$sql = "SELECT activated from freebox_users where user_id = $userId";
	$row = execOneSQL($sql);		
	return($row['activated'] === $status);
}

function reactivate($fxCredentials) {
	$userId = getUserId($fxCredentials);
	$sql = "UPDATE freebox_users SET activated = 'Y' where user_id = $userId";
	execSQL($sql);
	logFxAction("reactivate", $fxCredentials, "Reactivate " . $fxCredentials['freeboxurl']);
}


function askresetpassword($email) {
	$sql = "SELECT user_id, token, activated FROM freebox_users WHERE email = '$email'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_NOT_EXIST', array($email)));
		
	if($row['activated'] == 'N')
	throw new FreeboxWifiSchedulerException(translate('ACCOUNT_NOT_ACTIVATED', array($email)));

	$userId = $row['user_id'];
	$token = getUniqueCode(64);
	$sql = "UPDATE freebox_users SET token = '$token' where user_id = $userId";
	execSQL($sql);
	
	$resetpwdUrl = curPageURL() . "?action=resetpassword&email=$email&token=$token";
	$subject = "Reset freebox account";
	$msg = "To reset your account password, please go to $resetpwdUrl";
	
	$message = $msg;
	$address['to'] = $email;
	$address['from'] = "freebox@" . getServerAdress();
	$content_type = "Text/plain";
	formatted_mail($subject, $message, $address, $content_type);
	
	logFxAction("askresetpassword", null, "Send mail to " . $email);
}

function resetpassword($email, $token, $pass) {
	
	$sql = "SELECT user_id, token, activated FROM freebox_users WHERE email = '$email'";
	$row = execOneSQL($sql);
	if(!is_array($row))
	throw new FreeboxWifiSchedulerException(translate('EMAIL_NOT_EXIST', array($email)));

	if($row['token'] !== $token)
	throw new FreeboxWifiSchedulerException(translate('EMAIL_RESET_ERROR', array($email)));

	if(!isset($pass))
	throw new FreeboxWifiSchedulerException(translate('PWD_EMPTY'));
	
	if(strlen($pass) < 4)
	throw new FreeboxWifiSchedulerException(translate('PWD_TOO_SHORT', array(4)));
	
	$userId = $row['user_id'];
	$token = getUniqueCode(64);
	$sql = "UPDATE freebox_users SET pass = '$pass', token = '$token'  where user_id = $userId";
	execSQL($sql);
	logFxAction("resetpassword", null, "Reset password for " . $email);
}

function actionRequireAuthentication($action)
{
	switch($action) {
	case 'enablewifi':
	case 'disablewifi':
	case 'wifistatus':
	case 'clientlist':
	case 'refreshclientlist':
	case 'setnofilter':
	case 'activatewhilelist':		
	case 'activateblacklist':
	case 'filterstatus':
	case 'enableparentalcontrol':
	case 'disableparentalcontrol':
	case 'parentalcontrolstatus':
	case 'unregister':
	case 'suspend':
	case 'reactivate':
	case 'remoteconnexionstatus':
	case 'enableremoteconnexion':
	case 'disableremoteconnexion':
	case 'enablepornprotection':
	case 'disablepornprotection':
	case 'pornprotectionstatus':
	case 'tagmac':
	case 'addmactowhitelist':
	case 'removemactowhitelist':
	case 'addmactoblacklist':
	case 'removemactoblacklist':
	case 'isactive':
	case 'issuspended':
		return true;
	default:
		return false;
	}
}

/*********************************************************************************************/
/* Tools
/*********************************************************************************************/

function translate($msgId, $arg = array(), $lang = LANGUAGE) {
	$TRANSLATE['en']['NO_MAC_TAG'] = 'Tag[%s] does not exits';
	$TRANSLATE['fr']['NO_MAC_TAG'] = 'Le tag[%s] n\'existe pas';
	
	$TRANSLATE['en']['INVALID_FILTER_STATUS'] = 'Filter status [%d] is not valid';
	$TRANSLATE['fr']['INVALID_FILTER_STATUS'] = 'Le status de filtre [%d] n\'est pas valide';
	
	$TRANSLATE['en']['CANNOT_CHANGE_REMOTE_CONNEXION'] = 'Cannot change remote connexion state';
	$TRANSLATE['fr']['CANNOT_CHANGE_REMOTE_CONNEXION'] = 'La connexion à distance n\'est pas midifiable';
	
	$TRANSLATE['en']['FREEBOX_PWD_CHANGED'] = 'Freebox password was changed';
	$TRANSLATE['fr']['FREEBOX_PWD_CHANGED'] = 'Le mot de passe de la freebox a été modifié';
	
	$TRANSLATE['en']['BAD_IP_OR_PWD'] = 'Bad password or ip';
	$TRANSLATE['fr']['BAD_IP_OR_PWD'] = 'Le mot de passe ou l\'adresse de la freebox est erroné';

	$TRANSLATE['en']['CANNOT_DISCONNECT'] = 'Cannot disconnect';
	$TRANSLATE['fr']['CANNOT_DISCONNECT'] = 'La déconnexion a échouée';
	
	$TRANSLATE['en']['EMAIL_PWD_BAD'] = 'Email [%s] does not exits or bad password';
	$TRANSLATE['fr']['EMAIL_PWD_BAD'] = 'L\'email [%s] n\'est pas valide ou le mot de passe n\'est pas correct';

	$TRANSLATE['en']['ACCOUNT_NOT_ACTIVATED'] = 'Email [%s] is not activated';
	$TRANSLATE['fr']['ACCOUNT_NOT_ACTIVATED'] = 'L\'email [%s] n\'a pas été activé';
	
	$TRANSLATE['en']['URL_BAD'] = 'Url [%s] does not exits';
	$TRANSLATE['fr']['URL_BAD'] = 'L\'Url [%s] est erroné';
	
	$TRANSLATE['en']['EMAIL_EMPTY'] = 'Email is empty';
	$TRANSLATE['fr']['EMAIL_EMPTY'] = 'L\'email n\'est pas renseigné';
	
	$TRANSLATE['en']['EMAIL_BAD'] = 'Email [%s] is not valid';
	$TRANSLATE['fr']['EMAIL_BAD'] = 'L\'email [%s] n\'est pas valide';
	
	$TRANSLATE['en']['EMAIL_ALREADY_USED'] = 'Email [%s] already used';
	$TRANSLATE['fr']['EMAIL_ALREADY_USED'] = 'L\'email [%s] est déjà utilisé';
	
	$TRANSLATE['en']['PWD_EMPTY'] = 'Password is empty';
	$TRANSLATE['fr']['PWD_EMPTY'] = 'Le mot de passe n\'est pas renseigné';
	
	$TRANSLATE['en']['PWD_TOO_SHORT'] = 'Password is too short, minimum is %d alphanumerics';
	$TRANSLATE['fr']['PWD_TOO_SHORT'] = 'Le mot de passe est trop court. Il faut au moins %d caractères';
	
	$TRANSLATE['en']['FREEBOX_URL_EMPTY'] = 'Freebox Url is empty';
	$TRANSLATE['fr']['FREEBOX_URL_EMPTY'] = 'L\'url de la freebox n\'est pas renseigné';

	$TRANSLATE['en']['FREEBOX_URL_BAD'] = 'Freebox Url [%s] is not valid';
	$TRANSLATE['fr']['FREEBOX_URL_BAD'] = 'L\'url de la freebox [%s] n\'est pas valide';

	$TRANSLATE['en']['FREEBOX_URL_ALREADY_USED'] = 'Freebox Url [%s] already used';
	$TRANSLATE['fr']['FREEBOX_URL_ALREADY_USED'] = 'L\'url de la freebox [%s] est déjà utilisé';

	$TRANSLATE['en']['FREEBOX_PWD_EMPTY'] = 'Freebox pass is empty';
	$TRANSLATE['fr']['FREEBOX_PWD_EMPTY'] = 'Le mot de passe de la freebox n\'est pas renseigné';

	$TRANSLATE['en']['FREEBOX_PWD_TOO_SHORT'] = 'Freebox password is too short, minimum is %d alphanumerics';
	$TRANSLATE['fr']['FREEBOX_PWD_TOO_SHORT'] = 'Le mot de passe de la freebox est trop court. Il faut au moins %d caractères';

	$TRANSLATE['en']['FREEBOX_CONNECT_ERROR'] = 'Cannot connect to freebox %s';
	$TRANSLATE['fr']['FREEBOX_CONNECT_ERROR'] = 'La freebox %s ne peut être joint';

	$TRANSLATE['en']['FREEBOX_PWD_BAD'] = 'Freebox password is not correct';
	$TRANSLATE['fr']['FREEBOX_PWD_BAD'] = 'Le mot de passe de la freebox n\'est pas valide';
	
	$TRANSLATE['en']['EMAIL_NOT_EXIST'] = 'Email [%s] does not exits';
	$TRANSLATE['fr']['EMAIL_NOT_EXIST'] = 'L\'email [%s] est inconnu';

	$TRANSLATE['en']['EMAIL_ACTIVATE_ERROR'] = 'Cannot activate email [%s]';
	$TRANSLATE['fr']['EMAIL_ACTIVATE_ERROR'] = 'L\'email [%s] ne peut-être activé';

	$TRANSLATE['en']['EMAIL_RESET_ERROR'] = 'Cannot reset password for email [%s]';
	$TRANSLATE['fr']['EMAIL_RESET_ERROR'] = 'Le mot de passe pour [%s] ne peut-être reinitalisé';
	
	$TRANSLATE['en']['EMAIL_ALREADY_ACTIVATED'] = 'Email [%s] is already activated';
	$TRANSLATE['fr']['EMAIL_ALREADY_ACTIVATED'] = 'L\'email [%s] est déjà activé';
	
	$TRANSLATE['en']['INTERNAL_ERROR'] = 'Internal error';
	$TRANSLATE['fr']['INTERNAL_ERROR'] = 'Error interne';
	
	$TRANSLATE['en']['URL_FETCH_ERROR'] = 'Cannot fetch [%s] because of [%s]';
	$TRANSLATE['fr']['URL_FETCH_ERROR'] = 'Durant le téléchargement de [%s], l\'erreur [%s] est survenu';	

	$TRANSLATE['en']['PWD_CHANGED'] = 'Password was changed';
	$TRANSLATE['fr']['PWD_CHANGED'] = 'Le mot de passe a été modifié';
	
	$TRANSLATE['en']['PWD_DIFFERENT'] = 'Passwords are not the same';
	$TRANSLATE['fr']['PWD_DIFFERENT'] = 'Les mots de passe sont différents';
	
	if(!isset($TRANSLATE[$lang][$msgId]))
			return "<<[$lang][$msgId]>>";
	
	return vsprintf($TRANSLATE[$lang][$msgId], $arg);
}

function FreeboxErrorHandler($errno, $errstr, $errfile, $errline) {
	if (!(error_reporting() & $errno)) {
		return false;
	}

	switch ($errno) {
	case E_USER_ERROR:			
		LogError("$errstr at $errfile:$errline");
		throw new FreeboxWifiSchedulerException(translate('INTERNAL_ERROR'));
		break;

	case E_USER_WARNING:
		LogError("WARN $errstr at $errfile:$errline");
		break;

	case E_USER_NOTICE:
		LogError("NOTICE $errstr at $errfile:$errline");
		break;

	default:
		LogError("$errstr at $errfile:$errline");
		break;
	}
	
	return true;
}

class FreeboxWifiSchedulerException extends Exception {
}

function logFxAction($action, $fxCredentials, $message) {
	if(isset($fxCredentials))
	LogForceInfo("[$action][fx:" . $fxCredentials['freeboxurl'] . "] $message");
	else
	LogForceInfo("[$action] $message");
}

function generateUrl($ip, $action, $param = '', $type = 'php') {
	if(isset($type) && strlen($type) > 0)
		return "http://$ip/$action.$type$param";
	else
		return "http://$ip/$action";
}

function checkHtmlResponse($url, &$response) {
	if ((isset($response['ERROR']) && strlen($response['ERROR']) > 0)) {
		LogError("[checkHtmlResponse] cannot connect to [$url] because of " . $response['ERROR']);
		throw new FreeboxWifiSchedulerException(translate("URL_FETCH_ERROR", array($url, $response['ERROR'])));
	}
	
	convertCharset($response['FILE']);
}

function postData($fxCredentials, $page, $extension, $data) {
	$url = generateUrl($fxCredentials['freeboxurl'], $page, '', $extension);
	
	//Do not display password
	$datadump = $data;
	unset($datadump['passwd']);
	unset($datadump['pass']);
	unset($datadump['password']);
	
	LogInfo("[postData] sending data into [$url] : " . print_r($datadump, true));
	$result = http_post_form($url, $url, $data);
	checkHtmlResponse($url, $result);
	
	return $result;
}

function extractForms(&$page) {

	$parser = new form_fields();
	
	$forms = parse_array($page, "<form", "</form>");
	$result = array();
	foreach ($forms as $form) {
		$result[] = $parser->form_to_data($form);
	}
	
	return $result;
}

function getFormData($fxCredentials, $page, $opt) {
	$ip = $fxCredentials['freeboxurl'];
	
	$url = generateUrl($ip, $page);
	$param = array('page' => $opt);
	LogInfo("[getFormData] extract data from [$url]");
	$result = http_get_form($url, $url, $param);
	checkHtmlResponse($url, $result);
	
	$formsdata = extractForms($result['FILE']);	
	$formdata = $formsdata[0]['data'];
	$data = array();
	foreach($formdata as $key => $value)
	{
		foreach($value as $subkey => $subvalue)
		{
			if($subkey == 'checked')
			{
				if($subvalue)
				$data[$key] = 'on';
				else
				unset($data[$key]);
			}
			else
			$data[$key] = $subkey;
		}
	}
	
	return $data;
}

/*********************************************************************************************/
/* Forms
/*********************************************************************************************/
function generateResetPasswordForm($email) {
	logFxAction("generateResetPasswordForm", null, "Generate pwd form for " . $email);
	
	echo "\n". '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"';
	echo "\n". '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	echo "\n". '<html xmlns="http://www.w3.org/1999/xhtml">';
	echo "\n". '<head>';
	echo "\n". '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	echo "\n". '<title>Pass</title>';
	echo "\n". '<style type="text/css">';
	echo "\n". 'label { ';
	echo "\n". 'display: inline-block;';
	echo "\n". 'width: 150px;';
	echo "\n". '}';
	echo "\n". '</style>';
	echo "\n". '</head>';
	echo "\n". '<body>';
	echo "\n". '<div>';
	echo "\n". "<h2>Modify pass for $email</h2>";
	echo "\n". '<form method="POST">';
    echo "\n". '<br />';
    echo "\n". '<label>Pass</label>';
    echo "\n". '<input type="password" name="pass" value="" />';
	echo "\n". '<br />';
    echo "\n". '<label>Retype Pass</label>';
    echo "\n". '<input type="password" name="pass2" value="" />';
    echo "\n". '<br/>';
    echo "\n". '<input type="submit" value="Appliquer" />';
    echo "\n". '<br/>';
	echo "\n". '</form>';
	echo "\n". '</div>';
	echo "\n". '</body>';
	echo "\n". '</html>';
}

function generateForm() {	
	$ACTION['noaction'] = '---------------- Select ----------------';
	$ACTION['enablewifi'] = 'Enable wifi';
	$ACTION['disablewifi'] = 'Disable wifi';
	$ACTION['wifistatus'] = 'Wifi status';
	
	$ACTION['action-wifi'] = '---------------- Wifi action ----------------';
	$ACTION['clientlist'] = 'Wifi Client List';
	$ACTION['refreshclientlist'] = 'Refresh Wifi Client List';
	
	$ACTION['action-mac'] = '---------------- Mac action ----------------';
	$ACTION['setnofilter'] = 'No mac filter';
	$ACTION['activatewhilelist'] = 'While list mac filter';
	$ACTION['activateblacklist'] = 'Black list mac filter';
	$ACTION['filterstatus'] = 'Mac filter status';
	$ACTION['tagmac'] = 'Tag mac address';
	$ACTION['addmactowhitelist'] = 'Add mac to white list';
	$ACTION['removemactowhitelist'] = 'Remove mac to white list';
	$ACTION['addmactoblacklist'] = 'Add mac to black list';
	$ACTION['removemactoblacklist'] = 'Remove mac to black list';
	
	$ACTION['action-parental'] = '---------------- Parental Control ----------------';
	$ACTION['enableparentalcontrol'] = 'Enable Parental Control';
	$ACTION['disableparentalcontrol'] = 'Disable Parental Control';
	$ACTION['parentalcontrolstatus'] = 'Parental Control status';
	
	$ACTION['action-remote'] = '---------------- Remote Connexion ----------------';
	$ACTION['enableremoteconnexion'] = 'Enable remote connexion';
	$ACTION['disableremoteconnexion'] = 'Disable remote connexion';
	$ACTION['remoteconnexionstatus'] = 'Remote connexion status';
	
	$ACTION['action-porn'] = '---------------- Porn filter ----------------';
	$ACTION['enablepornprotection'] = 'Enable Porn protection';
	$ACTION['disablepornprotection'] = 'Disable Porn protection';
	$ACTION['pornprotectionstatus'] = 'Porn protection status';
	
	$ACTION['action-account'] = '---------------- Account ----------------';
	$ACTION['register'] = 'Register';
	$ACTION['unregister'] = 'Unregister';
	$ACTION['activate'] = 'Activate';
	$ACTION['suspend'] = 'Suspend';
	$ACTION['reactivate'] = 'Reactivate';
	$ACTION['whatismyip'] = 'What is my ip';
	$ACTION['askresetpassword'] = 'Ask reset password';	
	$ACTION['isactive'] = 'Is active';
	$ACTION['issuspended'] = 'Is suspended';

	echo "\n". '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"';
	echo "\n". '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	echo "\n". '<html xmlns="http://www.w3.org/1999/xhtml">';
	echo "\n". '<head>';
	echo "\n". '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	echo "\n". '<title>Freebox management</title>';
	echo "\n". '<style type="text/css">';
	echo "\n". 'label { ';
	echo "\n". 'display: inline-block;';
	echo "\n". 'width: 150px;';
	echo "\n". '}';
	echo "\n". '</style>';
	echo "\n". '<script type="text/javascript">';                
	echo "\n". 'function EventChanged(selectEl)';
	echo "\n". '{';
	echo "\n". '  document.getElementById("email_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("email_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("email_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("pass_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("pass_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("pass_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxurl_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxurl_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxurl_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxpass_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxpass_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("freeboxpass_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("token_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("token_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("token_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("mac_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("mac_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("mac_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("tag_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("tag_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("tag_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("forcelog_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("forcelog_input").style.display =\'none\';';
	echo "\n". '  document.getElementById("forcelog_br").style.display =\'none\';';
	echo "\n". '  document.getElementById("force_label").style.display =\'none\';';
	echo "\n". '  document.getElementById("force_input").style.display =\'none\';';	
	echo "\n". '  document.getElementById("force_br").style.display =\'none\';';
	echo "\n". '  var text = selectEl.value;';
	echo "\n". '  if (text == "enablewifi" || text == "disablewifi" ||text == "wifistatus" ||text == "clientlist" ||text == "refreshclientlist" ||text == "setnofilter" ||text == "activatewhilelist" ||text == "activateblacklist" ||text == "filterstatus" ||text == "enableparentalcontrol" ||text == "disableparentalcontrol" ||text == "parentalcontrolstatus" ||text == "enableremoteconnexion" ||text == "disableremoteconnexion" ||text == "remoteconnexionstatus" ||text == "enablepornprotection" ||text == "disablepornprotection" ||text == "pornprotectionstatus" ||text == "suspend" ||text == "reactivate" ||text == "unregister" || text == "isactive" || text == "issuspended")';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';	
	echo "\n". '     }';
	echo "\n". '  	else if (text == "register")';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxurl_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxurl_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxurl_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxpass_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxpass_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("freeboxpass_br").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';	
	echo "\n". '     }';
	echo "\n". '  	else if (text == "activate")';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("token_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("token_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("token_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';	
	echo "\n". '     }';
	echo "\n". '  	else if (text == "askresetpassword")';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';	
	echo "\n". '     }';
	echo "\n". '  	else if (text == "tagmac")';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_br").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("mac_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("mac_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("mac_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("tag_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("tag_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("tag_br").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';
	echo "\n". '     }';
	echo "\n". '  	else if (text == "addmactowhitelist" || text == "removemactowhitelist" || text == "addmactoblacklist" || text == "removemactoblacklist" )';
	echo "\n". '     { ';
	echo "\n". '        document.getElementById("email_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("email_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("pass_br").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("mac_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("mac_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("mac_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_input").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("forcelog_br").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_label").style.display =\'inline-block\';';
	echo "\n". '        document.getElementById("force_input").style.display =\'inline-block\';';	
	echo "\n". '        document.getElementById("force_br").style.display =\'inline-block\';';
	echo "\n". '     }';	
	echo "\n". '}';
	echo "\n". '</script>	';
	echo "\n". '</head>';
	echo "\n". '<body>';
	echo "\n". '<div class="bloc" >';
	echo "\n". '<h2>Freebox management</h2>';
	echo "\n". '<form method="POST">';
    echo "\n". '<label>Action</label>';
    echo "\n". '<select id="action" name="action"  width="300" onchange="EventChanged(this)" style="width: 300px">';
	foreach($ACTION as $key => $value)
		echo "<option value='$key' >$value</option>";
    echo "\n". '</select>';
    echo "\n". '<br />';
    echo "\n". '<label id="email_label" style=\'display:none\'>Email</label>';
    echo "\n". '<input type="text" style="width: 300px;display:none" id="email_input" name="email" value="" />';
    echo "\n". '<br id="email_br"  style=\'display:none\'/>';
    echo "\n". '<label id="pass_label"  style=\'display:none\'>Pass</label>';
    echo "\n". '<input type="password" style="width: 300px;display:none" id="pass_input" name="pass" value="" />';
    echo "\n". '<br id="pass_br"  style=\'display:none\'/>';
    echo "\n". '<label id="freeboxurl_label"  style=\'display:none\'>Freebox IP</label>';
    echo "\n". '<input type="text" style="width: 300px;display:none" id="freeboxurl_input" name="freeboxurl" value="" />';
    echo "\n". '<br id="freeboxurl_br"  style=\'display:none\'/>';
    echo "\n". '<label id="freeboxpass_label"  style=\'display:none\'>Freebox Pass</label>';
    echo "\n". '<input type="password" style="width: 300px;display:none" id="freeboxpass_input" name="freeboxpass" value="" />';
    echo "\n". '<br id="freeboxpass_br"  style=\'display:none\'/>';
    echo "\n". '<label id="token_label"  style=\'display:none\'>Token</label>';
    echo "\n". '<input type="text" style="width: 300px;display:none" id="token_input" name="token" value="" />';
    echo "\n". '<br id="token_br" style=\'display:none\'/>';
    echo "\n". '<label id="mac_label"  style=\'display:none\'>Mac</label>';
    echo "\n". '<input type="text" style="width: 300px;display:none" id="mac_input" name="mac" value="" />';
    echo "\n". '<br id="mac_br"  style=\'display:none\'/>';
	echo "\n". '<label id="tag_label"  style=\'display:none\'>Tag</label>';
    echo "\n". '<input type="text" style="width: 300px;display:none" id="tag_input" name="tag" value="" />';
    echo "\n". '<br id="tag_br"  style=\'display:none\'/>';
	echo "\n". '<label id="forcelog_br"  style=\'display:none\'></label>';
	echo "\n". '<input type="checkbox" name="forcelog" id="forcelog_input" style=\'display:none\'/>';
    echo "\n". '<label id="forcelog_label" style=\'display:none\'>Log</label>';
	echo "\n". '<input type="checkbox" name="force" id="force_input" style=\'display:none\'/>';
    echo "\n". '<label id="force_label" style=\'display:none\'>Force action</label>';    
    echo "\n". '<br id="force_br" style=\'display:none\'/>';
    echo "\n". '<input type="submit" value="Appliquer" />';
    echo "\n". '<br/>';
	echo "\n". '</form>';
	echo "\n". '</div>';
	echo "\n". '</body>';
	echo "\n". '</html>';
}

/*********************************************************************************************/
/* Initialization
/*********************************************************************************************/
error_reporting(E_ALL);
ini_set('max_execution_time', 30 * 60);
ini_set('memory_limit','256M');
$old_error_handler = set_error_handler("FreeboxErrorHandler");

/*
-- 
-- Structure de la table `freebox_macs`
-- 

CREATE TABLE `freebox_macs` (
  `user_id` int(8) NOT NULL,
  `mac` char(17) character set utf8 collate utf8_unicode_ci NOT NULL,
  `tag` varchar(64) character set utf8 collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`mac`,`user_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

-- --------------------------------------------------------

-- 
-- Structure de la table `freebox_scheduler`
-- 

CREATE TABLE `freebox_scheduler` (
  `user_id` int(11) NOT NULL,
  `mac` char(17) character set utf8 collate utf8_unicode_ci default NULL,
  `rule` varchar(1024) collate latin1_general_ci NOT NULL,
  UNIQUE KEY `user_id_2` (`user_id`,`mac`),
  KEY `mac` (`mac`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

-- --------------------------------------------------------

-- 
-- Structure de la table `freebox_users`
-- 

CREATE TABLE `freebox_users` (
  `user_id` int(11) NOT NULL auto_increment,
  `email` varchar(64) collate latin1_general_ci NOT NULL,
  `pass` varchar(64) collate latin1_general_ci NOT NULL,
  `freeboxurl` varchar(64) collate latin1_general_ci NOT NULL,
  `freeboxpass` varchar(64) collate latin1_general_ci NOT NULL,
  `token` varchar(64) collate latin1_general_ci NOT NULL,
  `activated` char(1) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`user_id`),
  UNIQUE KEY `freeboxurl` (`freeboxurl`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=8 ;

-- 
-- Contraintes pour les tables exportées
-- 

-- 
-- Contraintes pour la table `freebox_macs`
-- 
ALTER TABLE `freebox_macs`
  ADD CONSTRAINT `freebox_macs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `freebox_users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- 
-- Contraintes pour la table `freebox_scheduler`
-- 
ALTER TABLE `freebox_scheduler`
  ADD CONSTRAINT `freebox_scheduler_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `freebox_users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `freebox_scheduler_ibfk_2` FOREIGN KEY (`mac`) REFERENCES `freebox_macs` (`mac`) ON DELETE CASCADE ON UPDATE CASCADE;
*/
	
/*********************************************************************************************/
/* Main
/*********************************************************************************************/

$action = getValue('action');
if(!isset($action))
	$action = getValueGET('action');

$currentHour = date("H:i:s");
$forcelog = getValue('forcelog', 0, true);
if($forcelog)
$_GET['forcelog'] = 1;

$user = null;
$pass = null;
$force = getValue('force');

if(!isset($action)) {
	if((($currentHour >= "01:00:00") && ($currentHour < "01:02:00"))
			|| (($currentHour >= "07:45:00") && ($currentHour < "07:47:00"))
			|| isset($force) )
	{
		if (($currentHour >= "01:00:00") && ($currentHour < "07:45:00"))
		$action = 'disablewifi';
		else
		$action = 'enablewifi';
		
		define(LANGUAGE, 'en');
		$user = "mohamed.elouadi@gmail.com";
		$pass = "Elonux79";
		LogForceInfo("It's time to $action for $user");
	}
}

startChronometer("freebox");
$result = array();
$hasToDisconnect = false;
$fxCredentials = array();
$auth = actionRequireAuthentication($action);

try
{
	if($auth) {
		$user = getValue('email', $user);
		$pass = getValue('pass', $pass);
		$fxCredentials = getFreeboxCredentials($user, $pass);
		$fxCredentials['logout'] = connect($fxCredentials, true);
		$hasToDis = true;
	}
	
	switch($action) {
	case 'enablewifi':
	case 'disablewifi':
		setWifiStatus($fxCredentials, $action == 'enablewifi');
		
	case 'wifistatus':
		$status = getWifiStatus($fxCredentials);
		$result['wifi'] = $status ? 'on': 'off';
		logFxAction("getWifiStatus", $fxCredentials, "Wifi status is " . ($status ? 'on' : 'off'));
		break;
		
	case 'clientlist':
	case 'refreshclientlist':
		$result['clients'] = getMacList($fxCredentials);
		if($action == 'refreshclientlist')
		refreshMacList($fxCredentials, $result['clients']);
		break;
		
	case 'setnofilter':
	case 'activatewhilelist':		
	case 'activateblacklist':
		setFilterStatus($fxCredentials, ($action == 'setnofilter') ? 0 : (($action == 'activatewhilelist') ? 1 : 2));
		
	case 'filterstatus':
		$status = getFilterStatus($fxCredentials);
		$result['filter'] = $status;
		logFxAction("getFilterStatus", $fxCredentials, "Filter status is $status");
		break;
		
	case 'enableparentalcontrol':
	case 'disableparentalcontrol':
		setParentalControlStatus($fxCredentials, $action == 'enableparentalcontrol');
		
	case 'parentalcontrolstatus':
		$status = getParentalControlStatus($fxCredentials);
		$result['parentalcontrol'] = $status ? 'on': 'off';
		logFxAction("getParentalControlStatus", $fxCredentials, "Parental control status is " . ($status ? 'on' : 'off'));
		break;
		
	case 'enableremoteconnexion':
	case 'disableremoteconnexion':
		setRemoteConnexionStatus($fxCredentials, $action == 'enableremoteconnexion');
		
	case 'remoteconnexionstatus':
		$status = getRemoteConnexionStatus($fxCredentials);
		$result['remoteconnextion'] = $status ? 'on': 'off';
		logFxAction("getRemoteConnexionStatus", $fxCredentials, "Remote connexion status is " . ($status ? 'on' : 'off'));	
		break;
		
	case 'register':
		$email = getValue('email');
		$pass = getValue('pass');
		$freeboxurl = getValue('freeboxurl');
		$freeboxpass = getValue('freeboxpass');
		register($email, $pass, $freeboxurl, $freeboxpass);
		break;
		
	case 'unregister':
		unregister($fxCredentials);
		break;
		
	case 'activate':
		$email = getValueGET('email');
		$token = getValueGET('token');	
		activate($email, $token);
		break;
		
	case 'suspend':
		suspend($fxCredentials);
		break;
		
	case 'reactivate':
		reactivate($fxCredentials);
		break;
		
	case 'whatismyip':
		$result['ip'] = getClientIP();
		break;
		
	case 'enablepornprotection':
	case 'disablepornprotection':
		setPornProtectionStatus($fxCredentials, $action == 'enablepornprotection');
		
	case 'pornprotectionstatus':
		$status = getPornProtectionStatus($fxCredentials);
		$result['pornprotection'] = $status ? 'on': 'off';
		logFxAction("getPornProtectionStatus", $fxCredentials, "Porn protection status is " . ($status ? 'on' : 'off'));
		break;
		
	case 'askresetpassword':
		$email = getValue('email');
		askresetpassword($email);
		break;
		
	case 'resetpassword':
		$email = getValueGET('email');
		$token = getValueGET('token');
		$pass = getValue('pass');
		$pass2 = getValue('pass2');
		$errmsg = null;
		$displayForm = true;
		if(isset($pass) && ($pass === $pass2) ) {
			try{
				resetpassword($email, $token, $pass);
				echo translate("PWD_CHANGED");
				$displayForm = false;
			}
			catch(Exception $e)
			{
				$errmsg = $e->getMessage();
			}
		}
		
		if(isset($errmsg) || ($displayForm === true))
		{
			if($pass !== $pass2)
				echo  '<p style=\'color:red;\'>'. translate("PWD_DIFFERENT") . '<p>';
			if(isset($errmsg))
				echo  '<p style=\'color:red;\'>'. $errmsg . '<p>';
			generateResetPasswordForm($email);
		}
		die();
		break;
		
	case "isactive":
		$result['status'] = checkstatus($fxCredentials, 'Y');
		break;
		
	case "issuspended":
		$result['status'] = checkstatus($fxCredentials, 'S');
		break;
		
	case 'tagmac':
		$mac = getValue('mac');
		$tag = getValue('tag');
		tagMacAddress($fxCredentials, $mac, $tag);
		break;
		
	case 'addmactowhitelist':
		$mac = getValue('mac');
		addMacToWhiteList($fxCredentials, $mac);
		break;
	
	case 'removemactowhitelist':
		$mac = getValue('mac');
		removeMacFromWhiteList($fxCredentials, $mac);
		break;
		
	case 'addmactoblacklist':
		$mac = getValue('mac');
		addMacToBlackList($fxCredentials, $mac);
		break;
	
	case 'removemactoblacklist':
		$mac = getValue('mac');
		removeMacFromBlackList($fxCredentials, $mac);
		break;
		
	case 'publickey':
		$appid = getValueGET('appid');
		if(!RSA_IsCertificatExist($appid))
			RSA_GenerateCertificat($appid, 365);
		die(RSA_GetPublicKey($appid));
		break;
		
	default:
		generateForm();
		die();
	}
	
	if($auth)
	disconnect($fxCredentials);
}
catch(Exception $e)
{
	if($hasToDisconnect)
	disconnect($fxCredentials);
	$result['error'] = $e->getMessage();
	LogError($e->getMessage());
}

$result['elapsedTime'] = stopChronometer("freebox");

echo json_encode($result);

?>